﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Collections;

namespace CarbonMeter
{
    public partial class LicensingManagerForm : Form
    {
        // SDK API Filename Constante
        private const string DLLName = "XXXXX.dll";

        // Declarations SerialShield API
        [DllImport(DLLName, EntryPoint = "GetMachineID", ExactSpelling = false, CallingConvention = CallingConvention.StdCall)]
        static extern string GetMachineID();

        [DllImport(DLLName, EntryPoint = "SSUser", ExactSpelling = false, CallingConvention = CallingConvention.StdCall)]
        static extern int SSUser(string FullName, string Key, string SerialID);

        [DllImport(DLLName, EntryPoint = "SS_TrialExpired", ExactSpelling = false, CallingConvention = CallingConvention.StdCall)]
        static extern bool SS_TrialExpired();

        [DllImport(DLLName, EntryPoint = "SS_RemoveKey", ExactSpelling = false, CallingConvention = CallingConvention.StdCall)]
        static extern bool SS_RemoveKey();

        [DllImport(DLLName, EntryPoint = "SS_IsUnlocked", ExactSpelling = false, CallingConvention = CallingConvention.StdCall)]
        static extern bool SS_IsUnlocked();

        [DllImport(DLLName, EntryPoint = "SS_LicenseInfo", ExactSpelling = false, CallingConvention = CallingConvention.StdCall)]
        static extern string SS_LicenseInfo();

        [DllImport(DLLName, EntryPoint = "SS_R", ExactSpelling = false, CallingConvention = CallingConvention.StdCall)]
        static extern int SS_R(string Name, string Key);

        [DllImport(DLLName, EntryPoint = "SS_TrialMode", ExactSpelling = false, CallingConvention = CallingConvention.StdCall)]
        static extern int SS_TrialMode();


        // TripleDES Encryption Engine - Fast String Protection
        [DllImport(DLLName, EntryPoint = "TripleDESEncrypt", ExactSpelling = false, CallingConvention = CallingConvention.StdCall)]
        static extern string TripleDESEncrypt(string Text, string Key);

        [DllImport(DLLName, EntryPoint = "TripleDESDecrypt", ExactSpelling = false, CallingConvention = CallingConvention.StdCall)]
        static extern string TripleDESDecrypt(string Text, string Key);


        // Procedures SerialShield API
        [DllImport(DLLName, EntryPoint = "SS_Initialize", ExactSpelling = false, CallingConvention = CallingConvention.StdCall)]
        static extern void SS_Initialize();

        //her bir urun icin ayri ayri lisanslari tutuyor
        [DllImport(DLLName, EntryPoint = "SetApplicationInfo", ExactSpelling = false, CallingConvention = CallingConvention.StdCall)]
        static extern void SetApplicationInfo(string AppName, string AppKey);

        [DllImport(DLLName, EntryPoint = "Antidebugging", ExactSpelling = false, CallingConvention = CallingConvention.StdCall)]
        static extern void Antidebugging();

        [DllImport(DLLName, EntryPoint = "SS_DefaultKey", ExactSpelling = false, CallingConvention = CallingConvention.StdCall)]
        static extern void SS_DefaultKey(string Username, string LicenseKey, string SerialID);

        private static readonly ArrayList appName = new ArrayList();
        private static readonly ArrayList appKey = new ArrayList();
        private static LicenseStateEvent licenseEvent;
        private static readonly string dllKey = "GfsfWp2iETDOshK9VazRQQyeCp9WrC+yQCv8H9KWXmKuuJUsMTTiOno8Zql8d/g4iBVW2MynERtQgV6ggFNfiQ==";
        private static int appId;
       //private string owner

       //static constructor will execute only once
        static LicensingManagerForm()
        {
           //NOT: Herzaman arraydeki eleman sayisini gercek var olan lisasn sayisindan 1 fazla tut!!!
           appName.Add("Lisans1");
           appName.Add("Lisans2");
           appName.Add("Lisans3");
           appName.Add("unknown");
           appKey.Add("6GRBN8VU8TP142UXCLPJM584VWAJQF");
           appKey.Add("DJ9WW21483K97CNPBTFUXC3T42DRDE");
           appKey.Add("VDDHVMAHAT2YNMB8UHXGCNQ7DTMRLA");
           appKey.Add("unknown");
           appId = 0;
        }

        public LicensingManagerForm(LicenseStateEvent obj)
        {
            InitializeComponent();
            licenseEvent = obj;
        }

        public LicensingManagerForm()
        {
           InitializeComponent();
        }

        //Formu yuklemeden kontrol mekanizmasi
        public void LicenseCheck()
        {
            //Debug-->Exceptions-->Managed-->loader Lock kaldir
            // Antidebugging Protection
            Antidebugging();
            SS_R("TUBITAK UEKAE", dllKey);

            //TODO: uygulamanin ilk komutu SetApplicationInfo olmalidir.
            int i = 0;
            for (i = 0; i < 3; i++)
            {
                // Set your application settings for license detection
                SetApplicationInfo((string)appName[i], (string)appKey[i]);

                // Detection of Hardware (CPU Type, manufacturer's HDD serial, motherboard infos)
                GetMachineID();

                // Load Trial Key if no License is detected
                //SS_DefaultKey("","TL-B02C9766PlfzrafcR3BikOy4H/F0hr9FI81wWRo0","");

                // SerialShield Initialization (Startup only)
                SS_Initialize();

                if (SS_TrialMode() == 99)
                {
                    //uygulama sonlandirilmali
                    MessageBox.Show("Sistem Saatinin Geri Alındığı Tespit Edildi", "HATA", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    licenseEvent.licenseArg.licenseState = "systemClock";
                }
                else
                {
                    if (SS_TrialExpired())
                    {
                        //lisans yukleme ekrani gelmeli
                        MessageBox.Show("Deneme sürümünüz bitmiştir!", "UYARI", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        licenseEvent.licenseArg.licenseState = "trialExpire";
                        licenseEvent.licenseArg.productName = "unknown";
                        appId = i;
                        break;
                    }
                    else
                    {
                        if (!SS_IsUnlocked())
                        {
                            int trialMode = SS_TrialMode();
                            switch (trialMode)
                            {

                                case 1: //login menu yuklenmeli
                                    MessageBox.Show(SS_LicenseInfo() + " günlük kullanım hakkınız kaldı", "UYARI", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                    licenseEvent.licenseArg.licenseState = "trialDays";
                                    licenseEvent.licenseArg.productName = (string)appName[i];
                                    licenseEvent.licenseArg.permittedUse = int.Parse(SS_LicenseInfo());
                                    break;

                                case 2:
                                    //TODO: form yuklendiginde ve bu method calistiginda kullanim hakki 1er defa dusuyor boylece
                                    //2 defa dusmus oluyor, dikkat edilmeli
                                    MessageBox.Show(SS_LicenseInfo() + " günlük kullanım hakkınız kaldı", "UYARI", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                    licenseEvent.licenseArg.licenseState = "trialDate";
                                    licenseEvent.licenseArg.productName = (string)appName[i];
                                    licenseEvent.licenseArg.permittedUse = int.Parse(SS_LicenseInfo());
                                    break;

                                case 3:
                                    MessageBox.Show(SS_LicenseInfo() + " defa kullanım hakkınız kaldı", "UYARI", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                    licenseEvent.licenseArg.licenseState = "trialCount";
                                    licenseEvent.licenseArg.productName = (string)appName[i];
                                    licenseEvent.licenseArg.permittedUse = int.Parse(SS_LicenseInfo());
                                    break;

                                case 4: //login menu gelmeli
                                    //Hiçbir kısıtlama olmaksızın ücretsiz kullanım
                                    licenseEvent.licenseArg.licenseState = "trialUnlimited";
                                    licenseEvent.licenseArg.productName = (string)appName[i];
                                    licenseEvent.licenseArg.permittedUse = -1;
                                    break;

                                default:    //lisans yukleme ekrani gelmeli
                                    licenseEvent.licenseArg.licenseState = "trialUnknown";
                                    licenseEvent.licenseArg.productName = "unknown";
                                    licenseEvent.licenseArg.permittedUse = -1;
                                    break;
                            }
                            if (trialMode == 1 || trialMode == 2 || trialMode == 3 || trialMode == 4)
                            {
                                appId = i;
                                break;
                            }
                        }
                        else
                        {
                            //login menu yuklenmeli
                            licenseEvent.licenseArg.licenseState = "registered";
                            licenseEvent.licenseArg.productName = (string)appName[i];
                            licenseEvent.licenseArg.permittedUse = -1;
                            appId = i;
                            break;
                        }
                    }
                }
            }//end of for
            licenseEvent.licenseArg.eventOwner = "LicenseCheck";
            licenseEvent.OnLicenseEvent(this);

        }//end of method

        //TODO: lisans yukleme formu ana menuye konuldugunda ne olacagi dusunulmeli: parent kontrolu yapilabilir
        //Lisans yukle butonu
        private void button4_Click(object sender, EventArgs e)
        {
            int failNum = 0;
            int loginMenuCount = 0;

            for (int i = 0; i < 3; i++)
            {
                SetApplicationInfo((string)appName[i], (string)appKey[i]);
                GetMachineID();
                int ResultID = SSUser("", textBox2.Text, "");
               
                switch (ResultID)
                {
                    case 1:
                        switch (SS_TrialMode())
                        {
                              
                           //TODO: ayni lisansin 2 defa ust uste girilmesi durumu duzeltilmeli
                              //NOT: o anki lisansi yeni gelen lisasn ile karsilastirmak yetmez, kisi
                              //cok daha onceden aldigi lisansi yeni lisans olarak girebilir,
                              //tum lisans bilgileri loglanmali
                            case 1:     //login menu gelmeli
                                 licenseEvent.licenseArg.licenseState = "trialDays";
                                 licenseEvent.licenseArg.productName = (string)appName[i];
                                 licenseEvent.licenseArg.permittedUse = int.Parse(SS_LicenseInfo());
                                 textBox4.Text = SS_LicenseInfo() + " günlük kullanım hakkınız kaldı";
                                 loginMenuCount++;
                                 break;

                            case 2:     //login menu gelmeli
                                 textBox4.Text = SS_LicenseInfo() + " günlük kullanım hakkınız kaldı";
                                 licenseEvent.licenseArg.licenseState = "trialDate";
                                 licenseEvent.licenseArg.productName = (string)appName[i];
                                 licenseEvent.licenseArg.permittedUse = int.Parse(SS_LicenseInfo());
                                 loginMenuCount++;
                                 break;

                            case 3:     //login menu gelmeli
                                 licenseEvent.licenseArg.licenseState = "trialCount";
                                 licenseEvent.licenseArg.productName = (string)appName[i];
                                 licenseEvent.licenseArg.permittedUse = int.Parse(SS_LicenseInfo());
                                 textBox4.Text = SS_LicenseInfo() + " defa kullanım hakkınız kaldı";
                                 loginMenuCount++;
                                 break;

                            case 4:     //login menu gelmeli
                                 licenseEvent.licenseArg.licenseState = "trialUnlimited";
                                 licenseEvent.licenseArg.productName = (string)appName[i];
                                 licenseEvent.licenseArg.permittedUse = -1;
                                 textBox4.Text = "Hiçbir kısıtlama olmaksızın ücretsiz kullanım";
                                 loginMenuCount++;
                                 break;

                            case 5:     //lisans yukleme durmali
                                licenseEvent.licenseArg.licenseState = "sameLicNumber";
                                licenseEvent.licenseArg.productName = "unknown";
                                licenseEvent.licenseArg.permittedUse = -1;
                                textBox4.Text = "Bu seri numarası daha önce kullanıldı, tekrar kullanılamaz";
                                break;

                            case 99:    //uygulama sonlandirilmali
                                 licenseEvent.licenseArg.licenseState = "systemClock";
                                 licenseEvent.licenseArg.productName = "unknown";
                                 textBox4.Text = "Sistem saati geri alınmış";
                                 MessageBox.Show("Sistem Saatinin Geri Alındığı Tespit Edildi", "HATA", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                 break;

                            default:    //lisans yukleme durmali
                                 licenseEvent.licenseArg.licenseState = "trialUnknown";
                                 licenseEvent.licenseArg.productName = "unknown";
                                 licenseEvent.licenseArg.permittedUse = -1;
                                 textBox4.Text = "Lisans YOK!";
                                 break;
                        }
                        break;

                    case 3: //Incorrect key!
                        //Lisans yukleme ekrani durmali
                        licenseEvent.licenseArg.licenseState = "wrongLicNumber";
                        licenseEvent.licenseArg.productName = "unknown";
                        licenseEvent.licenseArg.permittedUse = -1;
                        failNum++;
                        break;

                    case 4:     //login menu cagirilmali
                        licenseEvent.licenseArg.licenseState = "registered";
                        licenseEvent.licenseArg.productName = (string)appName[i];
                        licenseEvent.licenseArg.permittedUse = -1;
                        textBox4.Text = "Lisans Başarı ile Yüklendi";
                        MessageBox.Show("Yazılım Kullanıma Hazır", "TEBRİKLER", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        loginMenuCount++;
                        break;

                    default:    //Lisans yukleme ekrani durmali
                        licenseEvent.licenseArg.licenseState = "invalidLicNumber";
                        licenseEvent.licenseArg.productName = "unknown";
                        licenseEvent.licenseArg.permittedUse = -1;
                        textBox4.Text = "Lütfen Geçerli Bir Lisans Yükleyiniz";
                        textBox2.Focus();
                        break;

                  }
                  if (failNum == (appKey.Count - 1))
                  {
                     textBox4.Text = "Gecersiz Lisans Kodu, Varsa Eski Lisansiniz Kullanılmaya Devam Edilecektir";
                     MessageBox.Show("Gecersiz Lisans Kodu", "UYARI", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                     textBox2.Focus();
                     break;
                  }
                  if (loginMenuCount > 0)
                  {
                     textBox3.Text = (string)appName[i];
                     textBox3.Update();
                     //eski lisanslari kaldirma
                     for (int k = 0; k < appKey.Count; k++)
                     {
                        if (k == i)
                        {
                           continue;
                        }
                        else
                        {
                           SetApplicationInfo((string)appName[k], (string)appKey[k]);
                           GetMachineID();
                           SS_Initialize();    //remove metodunun calisabilmesi icin eklendi
                           SS_RemoveKey();
                        }
                     }
                     //yeni lisans durumuna tekrar set etme
                     appId = i;  //yeni gecerli uygulama ID si degistirildi
                     SetApplicationInfo((string)appName[i], (string)appKey[i]);
                     GetMachineID();

                     if (this.Owner == null)   //dogrudan yukleme ekrani geliyor
                     {
                        licenseEvent.licenseArg.eventOwner = "FirstComingLicenseForm";
                     }
                     else    //NOT: main formun parent oldugu durum
                     {
                        licenseEvent.licenseArg.eventOwner = "ChildLicenseForm";
                     }
                     //TODO: bu eventin yeri degistirilmesi dusunulebilir
                     licenseEvent.licenseArg.productName = (string)appName[i];
                     licenseEvent.OnLicenseEvent(this);
                     break;
                } 
            }//for sonu
        }//end of method

        //Kopyala butonu
        private void button1_Click(object sender, EventArgs e)
        {
            textBox1.SelectAll();
            textBox1.Focus();
            Clipboard.SetDataObject(textBox1.Text);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
           
            int i = appId;
            //Debug-->Exceptions-->Managed-->loader Lock kaldir
            // Antidebugging Protection
            Antidebugging();
            SS_R("TUBITAK UEKAE", dllKey);

            //TODO: uygulamanin ilk komutu SetApplicationInfo olmalidir.
            // Set your application settings for license detection
            SetApplicationInfo((string)appName[i], (string)appKey[i]);

            // Detection of Hardware (CPU Type, manufacturer's HDD serial, motherboard infos)
            textBox1.Text = GetMachineID();

            // Load Trial Key if no License is detected
            //SS_DefaultKey("","TL-B02C9766PlfzrafcR3BikOy4H/F0hr9FI81wWRo0","");

            // SerialShield Initialization (Startup only)
            SS_Initialize();

            //TODO: form load sonuclarina da event eklenebilir?
            if (SS_TrialMode() == 99)
            {
               MessageBox.Show("Sistem Saatinin Geri Alındığı Tespit Edildi ");
            }
            else
            {
               if (SS_TrialExpired())
               {
                  textBox4.Text = "Deneme sürümünüz bitmiştir!";
                  textBox3.Text = (string)appName[i];
                  appId = i;
               }
               else
               {
                  if (!SS_IsUnlocked())
                  {
                        int trialMode = SS_TrialMode();
                        switch (trialMode)
                        {

                           case 1:
                              textBox4.Text = SS_LicenseInfo() + " günlük kullanım hakkınız kaldı";
                              break;

                           case 2:
                              textBox4.Text = SS_LicenseInfo() + " günlük kullanım hakkınız kaldı";
                              break;

                           case 3:
                              textBox4.Text = SS_LicenseInfo() + " defa kullanım hakkınız kaldı";
                              break;

                           case 4:
                              textBox4.Text = "Hiçbir kısıtlama olmaksızın ücretsiz kullanım";
                              break;

                           default:
                              textBox4.Text = "Lisans YOK!";
                              break;
                        }
                        if (trialMode == 1 || trialMode == 2 || trialMode == 3 || trialMode == 4)
                        {
                           textBox3.Text = (string)appName[i];
                           appId = i;
                        }
                  }
                  else
                  {
                        textBox4.Text = "Kayıtlı Versiyon";
                        textBox3.Text = (string)appName[i];
                        appId = i;
                  }
               }
            }
            textBox2.Select();
        }//end of method

        private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                e.Handled = true;
            }
        }

        private void LicensingManagerForm_FormClosing(object sender, FormClosingEventArgs e)
        {

        }
    }
}
